package com.yellowninja.backup.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;

import org.jdom.input.SAXBuilder;

/**
 * This class contains helper methods for backups.
 * 
 * @author Devin Gillman
 * 
 */
public class BackupUtils {
	@SuppressWarnings("unchecked")
	public static boolean runBackup(Backup backup) throws JDOMException,
			IOException, ParseException {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"MM/dd/yyyy HH:mm:ss z");

		// Check to make sure the directory and file exists.
		checkDirectory(backup.getSavePath());
		checkBackupFile(backup.getBackupFilePath());

		// Open the backup xml file.
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(new File(backup.getBackupFilePath()));

		// Then find the latest date.
		// First find the earliest backup.
		List<Element> backups = doc.getRootElement().getChildren();
		Iterator backupIt = backups.iterator();
		Calendar date = null;
		while (backupIt.hasNext()) {
			Object child = backupIt.next();
			if (child instanceof Element) {
				if (date != null) {
					Calendar newDate = Calendar.getInstance();
					newDate.setTime((Date) dateFormat.parse(((Element) child)
							.getAttribute("date").getValue()));
					if (newDate.after(date)) {
						date = newDate;
					}
				} else {
					date = Calendar.getInstance();
					date.setTime((Date) dateFormat.parse(((Element) child)
							.getAttribute("date").getValue()));
				}
			}
		}

		if (date == null)
			return true;

		// Last compare the dates.
		Calendar currentTime = Calendar.getInstance();
		float difference = (float) (currentTime.getTime().getTime() - date
				.getTime().getTime())
				/ (float) (24 * 3600 * 1000);

		return (difference > backup.getSchedule());
	}

	public static boolean checkBackupFile(String path) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			BufferedWriter out = new BufferedWriter(new FileWriter(file));
			out
					.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" standalone=\"no\"?>");
			out.newLine();
			out.write("<backups></backups>");
			out.close();
			return true;
		}

		return false;
	}

	public static boolean checkDirectory(String path) {
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
			return true;
		}

		return false;
	}
}
